<?php

namespace App\Http\Controllers\CRM;

use App\Enums\UserType;
use App\Helper\ApiResponseHelper;
use App\Http\Controllers\Controller;
use App\Http\Requests\CRM\UserRoleRequest;
use App\Http\Resources\CRM\UserRoleResource;
use App\Models\UserRole;
use Illuminate\Http\Request;

class UserRoleController extends Controller
{
    public function create(UserRoleRequest $request)
    {
        if ($request->type == UserType::System->value)
            return ApiResponseHelper::json([], 400, '超管无法创建');

        $role = UserRole::create($request->only([
            'name', 'remark', 'type', 'role_keys', 'parent_role_id',
        ]));

        return new UserRoleResource($role);
    }

    public function edit(UserRole $role, UserRoleRequest $request)
    {
        if ($role->type == UserType::System->value)
            return ApiResponseHelper::json([], 400, '超管无法编辑');

        $role->update($request->only([
//            'name', 'remark', 'type',
            'role_keys',
//            'parent_role_id',
        ]));

        return new UserRoleResource($role);
    }

    public function remove(UserRole $role)
    {
        if ($role->type == UserType::System->value)
            return ApiResponseHelper::json([], 400, '超管无法删除');

        $role->delete();
        return ApiResponseHelper::json([], 200, '删除成功');
    }

    public function getList()
    {
        $roles = UserRole::oldest()->get();

        return UserRoleResource::collection($roles);
    }

    public function getInfo(UserRole $role)
    {
        return new UserRoleResource($role);
    }

    private function getChildrenRoles(UserRole $role)
    {
        if (empty($role->childrenRoles)) {
            return;
        }

        foreach ($role->childrenRoles as $childRole) {

            if (!empty($childRole->childrenRoles)) {
                $this->getChildrenRoles($childRole);
            }
        }
    }
}
